package com.yzt.zhuju.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;

import com.yzt.p_base.utils.NetworkUtils;

/**
 * author : bob
 * date   : 2022/12/1
 * desc   :
 */
public class NetworkReceiver extends BroadcastReceiver {

    private boolean isConnected = true;

    private INetworkListener networkListener;

    public void setNetworkListener(INetworkListener networkListener) {
        this.networkListener = networkListener;
    }

    public void bind(Context context) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(this, intentFilter);
    }

    public void unbind(Context context) {
        context.unregisterReceiver(this);
        networkListener = null;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null) {
            return;
        }
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            boolean newConnectState = NetworkUtils.isNetAvailable();
            if (isConnected ^ newConnectState) {
                isConnected = newConnectState;
                if (networkListener != null) {
                    networkListener.onNetWorkStateChanged(isConnected);
                }
            }
        }
    }

    public interface INetworkListener {
        void onNetWorkStateChanged(boolean isAvailable);
    }
}

